//
//  VideoCaptureViewController.m
//  ChatForHot
//
//  Created by wr on 2018/10/18.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "HOTCHATVideoCaptureViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "CaptureToolKit.h"
#import <AVFoundation/AVFoundation.h>
#import "CameraRecorder.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <MediaPlayer/MediaPlayer.h>
#import "EMCDDeviceManager.h"
#import "XMPlayerView.h"
#import "VideoPlayingLineView.h"
#import "HCHelper.h"

#define TIMER_INTERVAL 0.05f
#define TAG_ALERTVIEW_CLOSE_CONTROLLER 10086

@interface HOTCHATVideoCaptureViewController ()<CameraRecorderDelegate>

@property (nonatomic, strong) UIView *HOTCHATmaskView;
@property (nonatomic, strong) CameraRecorder *recorder;
@property (nonatomic, strong) UIButton *HOTCHATdeleteButton;
@property (nonatomic, strong) UIButton *HOTCHATokButton;
@property (nonatomic, strong) UIButton *HOTCHATcloseButton;
@property (nonatomic, strong) UIButton *HOTCHATswitchButton;
@property (nonatomic, strong) UIButton *HOTCHATrecordButton;
@property (nonatomic, strong) UIView *HOTCHATpreview;
@property (nonatomic, strong) NSURL *fileURLs;
@property (nonatomic, strong) XMPlayerView *playerManager;
@property (nonatomic, strong) VideoPlayingLineView *HOTCHATlineview;
@property (nonatomic, assign) NSInteger HOTCHATviewMode;
@end

@implementation HOTCHATVideoCaptureViewController

- (void)HOTCHATdidInitialized {
    [super HOTCHATdidInitialized];
    
    self.view.backgroundColor = color(16, 16, 16, 1);
}

- (void)HOTCHATInsertSubViews{
    [super HOTCHATInsertSubViews];
    @weakify(self)
    [RACObserve(self, HOTCHATviewMode) subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        [self.view setNeedsUpdateConstraints];
        [self.view updateConstraintsIfNeeded];
        [UIView animateWithDuration:0.35 animations:^{
            [self.view layoutIfNeeded];
        }];
    }];
    
    [CaptureToolKit createVideoFolderIfNotExist];
    
    self.HOTCHATmaskView = [self getMaskView];
    [self.view addSubview:_HOTCHATmaskView];
    
    self.HOTCHATpreview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_SIZE.width, DEVICE_SIZE.height)];
    _HOTCHATpreview.clipsToBounds = YES;
    [self.view insertSubview:_HOTCHATpreview belowSubview:_HOTCHATmaskView];
    self.recorder = [[CameraRecorder alloc] init];
    _recorder.delegate = self;
    _recorder.previewLayer.frame = CGRectMake(0, 0, DEVICE_SIZE.width, DEVICE_SIZE.height);
    [self.HOTCHATpreview.layer addSublayer:_recorder.previewLayer];
    
    self.HOTCHATrecordButton = [[UIButton alloc] init];
    [_HOTCHATrecordButton setImage:[UIImage imageNamed:@"capture_video_nor"] forState:UIControlStateNormal];
    
    [_HOTCHATrecordButton addTarget:self action:@selector(longPressGestureRecognized:) forControlEvents:(UIControlEventTouchUpInside)];
    _HOTCHATrecordButton.adjustsImageWhenHighlighted = NO;
    [self.view insertSubview:_HOTCHATrecordButton belowSubview:_HOTCHATmaskView];
    
    _HOTCHATrecordButton.imageView.animationImages = @[[UIImage imageNamed:@"capture_capcam1"],[UIImage imageNamed:@"capture_capcam2"],[UIImage imageNamed:@"capture_capcam3"],[UIImage imageNamed:@"capture_capcam4"],[UIImage imageNamed:@"capture_capcam5"],[UIImage imageNamed:@"capture_capcam6"],[UIImage imageNamed:@"capture_capcam7"],[UIImage imageNamed:@"capture_capcam8"]];
    _HOTCHATrecordButton.imageView.animationDuration = 0.3;
    _HOTCHATrecordButton.imageView.animationRepeatCount = 1;
    
    self.HOTCHATdeleteButton = [[UIButton alloc] init];
    
    [_HOTCHATdeleteButton addTarget:self action:@selector(HOTCHATpressDeleteButton) forControlEvents:UIControlEventTouchUpInside];
    [_HOTCHATdeleteButton setImage:[UIImage imageNamed:@"capture_video_del"] forState:UIControlStateNormal];
    [_HOTCHATdeleteButton setImage:[UIImage imageNamed:@"capture_video_del_hig"] forState:UIControlStateHighlighted];
    [self.view insertSubview:_HOTCHATdeleteButton belowSubview:_HOTCHATmaskView];
    
    self.HOTCHATokButton = [[UIButton alloc] init];
    [_HOTCHATokButton setImage:[UIImage imageNamed:@"capture_video_save"] forState:UIControlStateNormal];
    [_HOTCHATokButton setImage:[UIImage imageNamed:@"capture_video_save_hig"] forState:UIControlStateHighlighted];
    [_HOTCHATokButton addTarget:self action:@selector(HOTCHATpressOKButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:_HOTCHATokButton belowSubview:_HOTCHATmaskView];
    
    self.HOTCHATcloseButton = [[UIButton alloc] init];
    [_HOTCHATcloseButton setImage:[UIImage imageNamed:@"capture_video_x"] forState:UIControlStateNormal];
    [_HOTCHATcloseButton setImage:[UIImage imageNamed:@"capture_video_x_hig"] forState:UIControlStateHighlighted];
    [_HOTCHATcloseButton addTarget:self action:@selector(HOTCHATpressCloseButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:_HOTCHATcloseButton belowSubview:_HOTCHATmaskView];
    
    self.HOTCHATswitchButton = [[UIButton alloc] init];
    [_HOTCHATswitchButton setImage:[UIImage imageNamed:@"capture_video_camera"] forState:UIControlStateNormal];
    [_HOTCHATswitchButton setImage:[UIImage imageNamed:@"capture_video_camera_hig"] forState:UIControlStateHighlighted];
    [_HOTCHATswitchButton addTarget:self action:@selector(HOTCHATpressSwitchButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:_HOTCHATswitchButton belowSubview:_HOTCHATmaskView];
    
    self.HOTCHATlineview = [[VideoPlayingLineView alloc] init];
    self.HOTCHATlineview.caColor = [UIColor whiteColor];
    [self.view addSubview:self.HOTCHATlineview];
    
    [self HOTCHATnormalView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self HOTCHAThideMaskView];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [self.HOTCHATcloseButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(10);
        make.top.equalTo(self.view).offset(34);
        make.width.height.mas_equalTo(40);
    }];
    
    [self.HOTCHATswitchButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-10);
        make.centerY.equalTo(self.HOTCHATcloseButton);
        make.width.height.mas_equalTo(40);
    }];
    [self.HOTCHATlineview mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(6);
    }];
    [self.HOTCHATrecordButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-40);
        make.centerX.equalTo(self.view);
    }];
    [self.HOTCHATdeleteButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(30);
        make.bottom.equalTo(self.view).offset(-30);
    }];
    [self.HOTCHATokButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-30);
        make.bottom.equalTo(self.view).offset(-30);
    }];
}

#pragma mark - CameraRecorderDelegate
- (void)HOTCHATdidStartCurrentRecording:(NSURL *)fileURL
{
    NSLog(@"录制视频ing: %@", fileURL);
}

- (void)HOTCHATdidFinishCurrentRecording:(NSURL *)outputFileURL duration:(CGFloat)videoDuration totalDuration:(CGFloat)totalDuration error:(NSError *)error {
    if (error) {
        NSLog(@"录制视频error:%@", error);
    } else {
        NSLog(@"录制视频finish: %@", outputFileURL);
        self.fileURLs = [self _convert2Mp4:outputFileURL];
        self.fileURLs = outputFileURL;
        [self playMP4];
    }
    if (totalDuration >= MAX_VIDEO_DUR) {
        [self HOTCHATpressOKButton];
    }
}

- (void)HOTCHATdidRemoveCurrentVideo:(NSURL *)fileURL totalDuration:(CGFloat)totalDuration error:(NSError *)error {
    if (error) {
        NSLog(@"删除视频error: %@", error);
    } else {
        NSLog(@"删除了视频ed: %@", fileURL);
        NSLog(@"现在视频lenth: %f", totalDuration);
    }
    if ([_recorder HOTCHATgetVideoCount] > 0) {}
    else {}
    _HOTCHATokButton.enabled = (totalDuration >= MIN_VIDEO_DUR);
}

- (void)HOTCHATdoingCurrentRecording:(NSURL *)outputFileURL duration:(CGFloat)videoDuration recordedVideosTotalDuration:(CGFloat)totalDuration {
    _HOTCHATokButton.enabled = !(videoDuration >= MIN_VIDEO_DUR);
    [self setTimes:videoDuration];
}

- (void)HOTCHATdidRecordingMultiVideosSuccess:(NSArray *)outputFilesURL {}

- (void)HOTCHATdidRecordingVideosSuccess:(NSURL *)outputFileURL {}

- (void)HOTCHATdidRecordingVideosError:(NSError*)error{}

- (void)HOTCHATdidTakePictureSuccess:(NSString *)outputFile {
    NSLog(@"TakePictureSuccess: %@", outputFile);
}

- (void)HOTCHATdidTakePictureError:(NSError*)error {
    NSLog(@"TakePictureError: %@", error.description);
}

#pragma mark - Actions
- (void)setTimes:(CGFloat)times{
    if (times >= MAX_VIDEO_DUR) {
        self.HOTCHATlineview.progress = 1;
    }else{
        CGFloat progress = (times / MAX_VIDEO_DUR);
        self.HOTCHATlineview.progress = progress;
    }
}
- (void)HOTCHATpressCloseButton
{
    [self HOTCHATdropTheVideo];
    [self HOTCHATcloseviewAndPlay];
}

- (void)HOTCHATpressSwitchButton {
    _HOTCHATswitchButton.selected = !_HOTCHATswitchButton.selected; {
        if (_recorder.HOTCHATisFrontCamera) {
            [_recorder HOTCHATopenTorch:NO];
        } else {}
    }
    [_recorder HOTCHATswitchCamera];
}

- (void)HOTCHATpressDeleteButton {
    if (self.playerManager.superview) {
        [self.playerManager tapAction];
        self.playerManager = nil;
    }
    [self HOTCHATdropTheVideo];
    [self HOTCHATnormalView];
    [[HCHelper sharedInstance] HOTCHATDeleteFileWithPath:self.fileURLs.absoluteString];
}

- (void)HOTCHATpressOKButton{
    [_recorder HOTCHATendVideoRecording];
    if (self.callBackBlock) {
        self.callBackBlock(YES, self.fileURLs);
    }
    [self HOTCHATcloseviewAndPlay];
}

- (void)HOTCHATdropTheVideo{
    [_recorder HOTCHATdeleteAllVideo];
}

- (void)HOTCHAThideMaskView{
    [UIView animateWithDuration:0.5f animations:^{
        CGRect frame = self.HOTCHATmaskView.frame;
        frame.origin.y = self.HOTCHATmaskView.frame.size.height;
        self.HOTCHATmaskView.frame = frame;
    }];
}

- (UIView *)getMaskView{
    UIView *maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEVICE_SIZE.width, DEVICE_SIZE.height + DELTA_Y)];
    maskView.backgroundColor = color(30, 30, 30, 1);
    return maskView;
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

- (BOOL)prefersStatusBarHidden{
    return YES;
}

#pragma mark - Tap Gesture

- (void)longPressGestureRecognized:(UIButton *)btn {
    BOOL btnSelected = btn.selected;
    btn.selected = !btnSelected;
    if (btnSelected) {
        [self.HOTCHATrecordButton setImage:[UIImage imageNamed:@"capture_video_nor"] forState:UIControlStateNormal];
        [self stopRecording];
        [self playingView];
    }else{
        [self.HOTCHATrecordButton setImage:[UIImage imageNamed:@"capture_video_ing"] forState:UIControlStateNormal];
        [self startRecording];
        [self recordingView];
        [self.HOTCHATrecordButton.imageView startAnimating];
    }
}

#pragma mark - Video Recording

- (void)startRecording{
    NSURL *fileURL = [NSURL fileURLWithPath:[CaptureToolKit getVideoSaveFilePathString]];
    [_recorder HOTCHATstartRecordingToOutputFileURL:fileURL];
}

- (void)stopRecording{
    [_recorder HOTCHATstopCurrentVideoRecording];
}

#pragma mark - View Mode

- (void)HOTCHATnormalView{
    self.HOTCHATcloseButton.hidden = NO;
    self.HOTCHATswitchButton.hidden = NO;
    self.HOTCHATlineview.hidden = YES;
    self.HOTCHATlineview.progress = 0;
    self.HOTCHATviewMode = 0;
}

- (void)recordingView{
    self.HOTCHATcloseButton.hidden = YES;
    self.HOTCHATswitchButton.hidden = YES;
    self.HOTCHATlineview.hidden = NO;
    self.HOTCHATviewMode = 1;
}

- (void)playingView{
    self.HOTCHATcloseButton.hidden = YES;
    self.HOTCHATswitchButton.hidden = YES;
    self.HOTCHATlineview.hidden = YES;
    self.HOTCHATviewMode = 2;
}

- (void)playMP4{
    self.playerManager = [[XMPlayerView alloc] init];
    self.playerManager.videoURL = self.fileURLs;
    self.playerManager.alpha = 0;
    self.playerManager.currentImage = [UIImage imageNamed:@"photo_placeholder"];
    self.playerManager.sourceImagesContainerView = self.view;;
    [self.playerManager HOTCHATShowInView:self.view];
    [self.view bringSubviewToFront:self.HOTCHATdeleteButton];
    [self.view bringSubviewToFront:self.HOTCHATokButton];
    [UIView animateWithDuration:0.15 animations:^{
        self.playerManager.alpha = 1;
    }];
}

- (NSURL *)_convert2Mp4:(NSURL *)movUrl {
    NSURL *mp4Url = nil;
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetLowQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset
                                                                              presetName:AVAssetExportPresetLowQuality];
        NSString *mp4Path = [NSString stringWithFormat:@"%@/%d%d.mp4", [EMCDDeviceManager dataPath], (int)[[NSDate date] timeIntervalSince1970], arc4random() % 100000];
        mp4Url = [NSURL fileURLWithPath:mp4Path];
        exportSession.outputURL = mp4Url;
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        dispatch_semaphore_t wait = dispatch_semaphore_create(0l);
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed: {
                    NSLog(@"failed, error:%@.", exportSession.error);
                } break;
                case AVAssetExportSessionStatusCancelled: {
                    NSLog(@"cancelled.");
                } break;
                case AVAssetExportSessionStatusCompleted: {
                    NSLog(@"completed.");
                } break;
                default: {
                    NSLog(@"others.");
                } break;
            }
            dispatch_semaphore_signal(wait);
        }];
        long timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
        if (timeout) {
            NSLog(@"timeout.");
        }
        if (wait) {
            wait = nil;
        }
    }
    
    return mp4Url;
}


#pragma mark - UPDATE
- (void)updateViewConstraints{
    [super updateViewConstraints];
    if (self.HOTCHATviewMode == 0 || self.HOTCHATviewMode == 1) {
        [self.HOTCHATdeleteButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.view.mas_left).offset(-10);
            make.bottom.equalTo(self.view).offset(-30);
        }];
        [self.HOTCHATokButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_right).offset(10);
            make.bottom.equalTo(self.view).offset(-30);
        }];
        
        [self.HOTCHATrecordButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view).offset(-40);
            make.centerX.equalTo(self.view);
        }];
        
    }else{
        [self.HOTCHATdeleteButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(30);
            make.bottom.equalTo(self.view).offset(-30);
        }];
        [self.HOTCHATokButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.view).offset(-30);
            make.bottom.equalTo(self.view).offset(-30);
        }];
        [self.HOTCHATrecordButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_bottom).offset(10);
            make.centerX.equalTo(self.view);
        }];
    }
}

- (void)HOTCHATcloseviewAndPlay{
    if (self.playerManager.superview) {
        [self.playerManager tapAction];
        self.playerManager = nil;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
